package bman.game.engine;

import java.awt.Image;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;

import javax.swing.ImageIcon;

public class ImageLibrary
{
	static Logger log = Logger.getLogger(ImageLibrary.class.getName());
	
	public static String imageDir = "images/";
	public static Map imageMap = new HashMap();
	
	public static Image getImage(String imageID, String bearing)
	{
		Image i = (Image)imageMap.get((imageID+bearing).toUpperCase());

		if(i == null)
		{
			i = (Image)imageMap.get((imageID).toUpperCase());
		}
		
		return i;
	}
	
	public static Image getImage(String imageID)
	{
		return (Image)imageMap.get(imageID.toUpperCase());
	}
	
	public static void loadImage(String imageID, String imagePath)
	{
		String id = imageID.toUpperCase();
		
		log.info("Loading "+id+", from "+imagePath);
		Image i = new ImageIcon(ImageLibrary.class.getResource(imagePath)).getImage();
		
		if(i == null || i.getHeight(null) < 0 || i.getWidth(null) < 0)
		{
			log.warning("No image loaded for "+id+" from "+imagePath);
		}
		else
		{
			imageMap.put(id,i);
		}
	}
	
	/**
	 * Loads images from a directory. Images can then be retrieved by using the
	 * getImage(imageName) method. The imageName shall be the filename of the image
	 * less the file extension. For example for the image file myImage.gif, the image name
	 * will be "myImage". ImageName is not case sensitive.
	 * 
	 * @return the number of images that has been loaded
	 * 
	 */
	public static int loadImagesFromDirectory(String directory)
	{
		File f = new File(directory);
		if(f.exists() && f.isDirectory())
		{
			int counter = 0;
			
			File[] files = f.listFiles();
			for(int i=0;i<files.length;i++)
			{
				int dot = files[i].getName().indexOf('.');
				String fn = files[i].getName().substring(0, dot);
				
				loadImage(fn, files[i].getAbsolutePath());
				counter++;
			}
			return counter;
		}
		else
		{
			log.warning("Unable to load any images, the path provided " +
					"either does not exist or is not a directory");
			return 0;			
		}
	}
}